package com.developer.platform.infrastructure.repository;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.developer.platform.domain.Role;
import com.developer.platform.domain.RoleMenu;
import com.developer.platform.domain.repository.IRoleRepository;
import com.developer.platform.infrastructure.data.mapper.RoleMapper;
import com.developer.platform.infrastructure.data.mapper.RoleMenuMapper;
import java.util.List;
import org.springframework.stereotype.Repository;

/**
 * @author ：qiaoliang
 * @date ：2020-11-09
 */
@Repository
public class RoleRepository implements IRoleRepository {

    private final RoleMapper roleMapper;
    private final RoleMenuMapper roleMenuMapper;

    public RoleRepository(RoleMapper roleMapper,
                          RoleMenuMapper roleMenuMapper) {
        this.roleMapper = roleMapper;
        this.roleMenuMapper = roleMenuMapper;
    }


    @Override
    public void save(Role role, List<Long> ids) {
        roleMapper.insert(role);
        roleMenu(role.getId(),ids);
    }

    @Override
    public void updateById(Role role, List<Long> ids) {
        roleMapper.updateById(role);
        roleMenu(role.getId(),ids);
    }

    @Override
    public void delete(long id) {
        roleMapper.deleteById(id);
        roleMenu(id,null);
    }

    private void roleMenu(long roleId, List<Long> ids){
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId, roleId);
        roleMenuMapper.delete(queryWrapper);
        if(CollUtil.isNotEmpty(ids)){
            ids.forEach(id->{
                roleMenuMapper.insert(new RoleMenu(roleId, id));
            });
        }
    }
}
